package org.jeecg.modules.solitaire_app.app.controller;

import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.solitaire_app.app.entity.*;
import org.jeecg.modules.solitaire_app.app.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 炼厂表
 * @Author: jeecg-boot
 * @Date: 2023-08-29
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "炼厂表")
@RestController
@RequestMapping("/app/ysyRefinery")
public class YsyRefineryController extends JeecgController<YsyRefinery, IYsyRefineryService> {
    @Autowired
    private IYsyRefineryService ysyRefineryService;
    @Autowired
    private IYsyRowMaterialRefineryService ysyRowMaterialRefineryService;
    @Autowired
    private IYsyOilRawMaterialPriceService ysyOilRawMaterialPriceService;
    @Autowired
    private IYsyDrivingTrackAddressService ysyDrivingTrackAddressService;
    @Autowired
    private IYsyRefineryPriceService ysyRefineryPriceService;

    /**
     * 分页列表查询
     *
     * @param ysyRefinery
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "炼厂表-分页列表查询")
    @ApiOperation(value = "炼厂表-分页列表查询", notes = "炼厂表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(YsyRefinery ysyRefinery,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<YsyRefinery> queryWrapper = QueryGenerator.initQueryWrapper(ysyRefinery, req.getParameterMap());
        Page<YsyRefinery> page = new Page<YsyRefinery>(pageNo, pageSize);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.eq("status", 1);
        IPage<YsyRefinery> pageList = ysyRefineryService.page(page, queryWrapper);

        pageList.getRecords().stream().forEach(item -> {
            List<String> oilListNames = ysyRowMaterialRefineryService.list(Wrappers.<YsyRowMaterialRefinery>lambdaQuery()
                    .eq(YsyRowMaterialRefinery::getRefineryId, item.getRefineryId())).stream().map(e -> e.getRawMaterialName()).collect(Collectors.toList());
            if (oilListNames.size() > 0) {
                item.setOilList(oilListNames.toString());
            }
        });

        return Result.ok(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param ysyRefinery
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "炼厂表-分页列表查询")
    @ApiOperation(value = "炼厂表-分页列表查询", notes = "炼厂表-分页列表查询")
    @GetMapping(value = "/wzlist")
    public Result<?> wzlist(YsyRefinery ysyRefinery,
                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                            HttpServletRequest req) {
        QueryWrapper<YsyRefinery> queryWrapper = QueryGenerator.initQueryWrapper(ysyRefinery, req.getParameterMap());
        Page<YsyRefinery> page = new Page<YsyRefinery>(pageNo, pageSize);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.eq("status", 0);
        IPage<YsyRefinery> pageList = ysyRefineryService.page(page, queryWrapper);

        pageList.getRecords().stream().forEach(item -> {
            List<String> oilListNames = ysyRowMaterialRefineryService.list(Wrappers.<YsyRowMaterialRefinery>lambdaQuery()
                    .eq(YsyRowMaterialRefinery::getRefineryId, item.getRefineryId())).stream().map(e -> e.getRawMaterialName()).collect(Collectors.toList());
            if (oilListNames.size() > 0) {
                item.setOilList(oilListNames.toString());
            }
        });

        return Result.ok(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param ysyRefinery
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "炼厂表-分页列表查询")
    @ApiOperation(value = "炼厂表-分页列表查询", notes = "炼厂表-分页列表查询")
    @GetMapping(value = "/oilList")
    public Result<?> oilList(YsyRefinery ysyRefinery,
                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                             HttpServletRequest req) {
        QueryWrapper<YsyRefinery> queryWrapper = QueryGenerator.initQueryWrapper(ysyRefinery, req.getParameterMap());
        Page<YsyRefinery> page = new Page<YsyRefinery>(pageNo, pageSize);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.eq("status", 1);
        IPage<YsyRefinery> pageList = ysyRefineryService.page(page, queryWrapper);

        pageList.getRecords().stream().forEach(item -> {
            List<String> oilListNames = ysyRowMaterialRefineryService.list(Wrappers.<YsyRowMaterialRefinery>lambdaQuery()
                    .eq(YsyRowMaterialRefinery::getRefineryId, item.getRefineryId())).stream().map(e -> e.getRawMaterialName()).collect(Collectors.toList());
            if (oilListNames.size() > 0) {
                item.setOilList(oilListNames.toString());
            }
            YsyOilRawMaterialPrice ysyOilRawMaterialPrice = ysyOilRawMaterialPriceService.getOneOilPriceByRefId(item.getRefineryId());
            if (ysyOilRawMaterialPrice != null) {
                item.setNewTime(ysyOilRawMaterialPrice.getCreateTime());
            }
        });

        return Result.ok(pageList);
    }

    /**
     * 分页列表查询
     *
     * @return
     */
    @AutoLog(value = "炼厂表-查询所有炼厂")
    @ApiOperation(value = "炼厂表-查询所有炼厂", notes = "炼厂表-查询所有炼厂")
    @GetMapping(value = "/getAllRefineryList")
    public Result<?> getAllRefineryList() {

        List<YsyRefinery> refineries = ysyRefineryService.list(Wrappers.<YsyRefinery>lambdaQuery()
                .eq(YsyRefinery::getStatus, 1));

        return Result.ok(refineries);
    }

    /**
     * 添加
     *
     * @param ysyRefinery
     * @return
     */
    @AutoLog(value = "炼厂表-添加")
    @ApiOperation(value = "炼厂表-添加", notes = "炼厂表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody YsyRefinery ysyRefinery) {
        ysyRefineryService.save(ysyRefinery);

        YsyDrivingTrackAddress ysyDrivingTrackAddress = new YsyDrivingTrackAddress();
        ysyDrivingTrackAddress.setAddress(ysyRefinery.getAddress());
        ysyDrivingTrackAddress.setAddressName(ysyRefinery.getAddress());
        ysyDrivingTrackAddress.setCreateTime(new Date());
        ysyDrivingTrackAddressService.save(ysyDrivingTrackAddress);

        return Result.ok(ysyRefinery.getRefineryId());
    }

    /**
     * 编辑
     *
     * @param ysyRefinery
     * @return
     */
    @AutoLog(value = "炼厂表-编辑")
    @ApiOperation(value = "炼厂表-编辑", notes = "炼厂表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody YsyRefinery ysyRefinery) {
        ysyRefineryService.updateRefinery(ysyRefinery);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "炼厂表-通过id删除")
    @ApiOperation(value = "炼厂表-通过id删除", notes = "炼厂表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        ysyRefineryService.remove(Wrappers.<YsyRefinery>lambdaQuery().eq(YsyRefinery::getRefineryId, id));

        //删除关联的炼厂报价
        ysyRefineryPriceService.remove(Wrappers.<YsyRefineryPrice>lambdaQuery()
                .eq(YsyRefineryPrice::getYsyOilTypeId, id));

        return Result.ok("删除成功!");
    }

    /**
     * 地图选点
     *
     * @param map
     * @return
     */
    @AutoLog(value = "炼厂表-地图选点")
    @ApiOperation(value = "炼厂表-地图选点", notes = "炼厂表-地图选点")
    @PostMapping(value = "/getRefineryListByMap")
    public Result<?> getRefineryListByMap(@RequestBody Map<String, Object> map) {
        return ysyRefineryService.getRefineryListByMap(map.get("address").toString());
    }

    /**
     * 通过id查询炼厂
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "炼厂表-通过id查询炼厂")
    @ApiOperation(value = "炼厂表-通过id查询炼厂", notes = "炼厂表-通过id查询炼厂")
    @GetMapping(value = "/getRefineryListByIds/{ids}")
    public Result<?> getRefineryListByIds(@PathVariable("ids") String ids) {
        List<YsyRefinery> ysyRefineries = new ArrayList<>();
        Arrays.asList(ids.split(",")).stream().forEach(item -> {
            YsyRefinery ysyRefinery = ysyRefineryService.getOne(Wrappers.<YsyRefinery>lambdaQuery()
                    .eq(YsyRefinery::getRefineryId, item));
            ysyRefineries.add(ysyRefinery);
        });
        return Result.ok(ysyRefineries);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "炼厂表-批量删除")
    @ApiOperation(value = "炼厂表-批量删除", notes = "炼厂表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.ysyRefineryService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "炼厂表-通过id查询")
    @ApiOperation(value = "炼厂表-通过id查询", notes = "炼厂表-通过id查询")
    @GetMapping(value = "/queryById/{id}")
    public Result<?> queryById(@PathVariable String id) {
        YsyRefinery ysyRefinery = ysyRefineryService.getOne(Wrappers.<YsyRefinery>lambdaQuery().eq(YsyRefinery::getRefineryId, id));
        return Result.ok(ysyRefinery);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param ysyRefinery
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, YsyRefinery ysyRefinery) {
        return super.exportXls(request, ysyRefinery, YsyRefinery.class, "炼厂表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, YsyRefinery.class);
    }

}
